package com.carrot.uaa.app;

import com.carrot.common.core.domain.R;
import com.carrot.uaa.constant.Oauth2Constants;
import com.carrot.uaa.entity.dto.TokenDTO;
import com.carrot.uaa.infrastructure.redis.RedisOperator;
import com.carrot.uaa.util.RedisUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * token相关业务
 */
@Service
@AllArgsConstructor
public class TokenAppServiceImpl implements TokenAppService{

    private final RedisOperator<Object> redisOperator;

    @Override
    public R delOnLineTokenByUserId(TokenDTO tokenDTO) {
        String userOnLineTokenKey = RedisUtils.getUserOnLineTokenKey(tokenDTO.getUserId());
        Map<String, Object> lineTokens = redisOperator.getMapHashAll(userOnLineTokenKey);
        if(lineTokens==null){
            return R.ok();
        }
        Set<String> keys = lineTokens.keySet();
        for (Iterator<String> iterator = keys.iterator(); iterator.hasNext(); ) {
            String key =  iterator.next();
            Map<String,String> value = (Map<String, String>) lineTokens.get(key);
            if(value!=null){
                String userOnLineAccessTokenKey = RedisUtils.getUserOnLineAccessTokenKey(value.get(Oauth2Constants.ACCESS_TOKEN));
                String userOnLineRefreshTokenKey = RedisUtils.getUserOnLineRefreshTokenKey(value.get(Oauth2Constants.REFRESH_TOKEN));
                redisOperator.delete(userOnLineAccessTokenKey,userOnLineRefreshTokenKey);
            }
        }
        redisOperator.delete(userOnLineTokenKey);
        return R.ok();
    }
}
